export default {
    install(Vue, config = {}) {

        let actions = {};

        /**
         * 整理配置
         */
        Object.entries(config.actions || {}).forEach(([key, url]) => {
            let action = typeof url === 'string' ? { url } : url,
                path = `/${(/(.*?\/\/[^/]*)?(.*)/gm).exec(action.url)[2]}`.replace(/\/+|\\+/gm, '/'),
                origin = ((/\w*?:?\/\/[^\/]*/gm).exec(action.url) || [action.origin || config.origin])[0].replace(/\/$/gm, '');
            actions[key] = Object.assign(action, { method: action.method || config.method || 'GET', url: origin + path });
        });

        /**
         * 请求动作
         * @param {*} action 动作
         * @param {Object} data 响应
         */
        Vue.prototype.$action = function (action, data) {
            return {
                response(res, rej = r => r()) {
                    return new Promise((resolve, reject) => {
                        config.request(Object.assign(actions[action], { data }), r => resolve(res(r)), r => reject(rej(r)));
                    }).then(()=>{},()=>{});
                }
            }
        }

        /**
         * 扩展
         */
        Vue.action = Object.assign(Vue.prototype.$action, {
            /**
             * 转换对象到FormData数据
             * @param {Object} target 目标对象
             * @return {FormData} 返回FormData数据
             */
            toFormData(target = {}) {
                return Object.entries(Vue.unfold(target)).reduce((p, [k, v]) => {
                    return p.append(k, v), p;
                }, new FormData());
            },
            /**
             * 转换对象到Query字符串
             * @param {Object} target 目标对象
             * @param {boolean} mode 模式
             * @return {string} 返回Query字符串
             */
            toQuery(target = {}, mode) {
                return mode ? Object.entries(Vue.unfold(target)).reduce((p, [k, v]) => {
                    return p.push(`${k}=${v}`), p;
                }, []).join('&') : String(Vue.url('', target)).replace(/^\?/gm, '');
            },
            /**
             * 解析Query字符串到对象
             * @param {string} query Query字符串
             * @return {Object} 返回解析后的对象
             */
            toObject(query = '') {
                return String(query).replace(/^\?/gm, '').split('&')
                    .filter(s => s)
                    .map(s => s.split('='))
                    .reduce((p, [k, v]) => {
                        if (k in p) {
                            p[k] instanceof Array ? p.push(v) : (p = [p[k], v]);
                        } else {
                            p[k] = v;
                        }
                        return p;
                    }, {});
            }
        });

    }
}